package com.dhnsoft.education.service.msm.impl;

import com.dhnsoft.education.handle.EduException;
import com.dhnsoft.education.utils.msm.ConstantPropertiesMsmUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 邮件发送实现类
 *
 * @author dhn
 * @date 2021/6/19 10:25
 */
@Service
public class EmailServiceImpl implements com.dhnsoft.education.service.msm.EmailService {
    @Autowired
    private JavaMailSender mailSender;

    @Override
    @Async
    public void sendEmail(String toEmail, String code) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper minehelper = new MimeMessageHelper(message, true);
            minehelper.setFrom(ConstantPropertiesMsmUtils.MAIL_USERNAME);
            minehelper.setTo(toEmail);
            //TODO 可能添加配置表，后台设置项目名 动态修改邮件发送模板
            minehelper.setSubject("智慧教育验证您的邮箱");
            minehelper.setText("来自智慧教育消息：您的验证码是" + code + "</br>"
                    + "请注意本平台绝不会以任何形式询问您的帐户密码和验证码。</br>"
                    + "本邮件由系统自动生成，请勿直接回复本邮件。</br>", true
            );
            Long startTime = System.currentTimeMillis();
            mailSender.send(message);
            Long endTime = System.currentTimeMillis();
            System.out.println("花费时间" + (endTime - startTime) + "ms");
        } catch (MessagingException e) {
            throw new EduException(20001, "邮件发送失败");
        }

    }
}
